package org.dromara.hm.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.service.ProductService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.hm.domain.HmProduct;
import org.dromara.hm.domain.bo.HmProductBo;
import org.dromara.hm.domain.vo.HmProductVo;
import org.dromara.hm.mapper.HmProductMapper;
import org.dromara.hm.service.IHmProductService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 产品信息Service业务层处理
 *
 * @author zy Hu
 * @date 2024-12-15
 */
@RequiredArgsConstructor
@Service
public class HmProductServiceImpl implements IHmProductService, ProductService
{

    private final HmProductMapper baseMapper;

    /**
     * 查询产品信息
     *
     * @param productId 主键
     *
     * @return 产品信息
     */
    @Override
    public HmProductVo queryById(Long productId)
    {
        return baseMapper.selectVoById(productId);
    }

    /**
     * 分页查询产品信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     *
     * @return 产品信息分页列表
     */
    @Override
    public TableDataInfo<HmProductVo> queryPageList(HmProductBo bo, PageQuery pageQuery)
    {
        LambdaQueryWrapper<HmProduct> lqw = buildQueryWrapper(bo);
        Page<HmProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的产品信息列表
     *
     * @param bo 查询条件
     *
     * @return 产品信息列表
     */
    @Override
    public List<HmProductVo> queryList(HmProductBo bo)
    {
        LambdaQueryWrapper<HmProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HmProduct> buildQueryWrapper(HmProductBo bo)
    {

        if(bo.getListingTime() != null ){
            LocalDateTime localDateTime = DateUtil.toLocalDateTime(bo.getListingTime());
            String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            bo.setListingTimeStr(format);
        }
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HmProduct> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(bo.getProductName()) && bo.getProductName().contains(";"))
        {
            List<String> productNames = StringUtils.splitList(bo.getProductName(), ";");
            lqw.in(HmProduct::getProductName, productNames);
        }
        else
        {
            lqw.like(StringUtils.isNotBlank(bo.getProductName()), HmProduct::getProductName, bo.getProductName());
        }

        lqw.eq(StringUtils.isNotBlank(bo.getSpecifications()), HmProduct::getSpecifications, bo.getSpecifications());
        lqw.eq(StringUtils.isNotBlank(bo.getPurchasePolicy()), HmProduct::getPurchasePolicy, bo.getPurchasePolicy());
        lqw.like(StringUtils.isNotBlank(bo.getShopSale()), HmProduct::getShopSale, bo.getShopSale());
        lqw.like(bo.getListingTime() != null, HmProduct::getListingTime, bo.getListingTimeStr());
        lqw.like(StringUtils.isNotBlank(bo.getShopSaleDesc()), HmProduct::getShopSaleDesc, bo.getShopSaleDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), HmProduct::getStatus, bo.getStatus());
        if(StringUtils.isNotBlank(bo.getProductType())){
           if("CP".equals(bo.getProductType())){
               lqw.eq(HmProduct::getIsCommercialProduct, true);
           }
           if("ZP".equals(bo.getProductType())){
               lqw.eq(HmProduct::getIsGiftProduct, true);
           }
        }

//        lqw.eq(StringUtils.isNotBlank(bo.getProductType()), HmProduct::getProductType, bo.getProductType());
        return lqw;
    }

    /**
     * 新增产品信息
     *
     * @param bo 产品信息
     *
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HmProductBo bo)
    {
        HmProduct add = MapstructUtils.convert(bo, HmProduct.class);
        validEntityBeforeSave(add);
        if (Boolean.TRUE.equals(add.getIsCommercialProduct())) {
            add.setProductType("CP");
        }
        if (Boolean.TRUE.equals(add.getIsGiftProduct())) {
            add.setProductType("ZP");
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag)
        {
            bo.setProductId(add.getProductId());
        }
        return flag;
    }

    /**
     * 修改产品信息
     *
     * @param bo 产品信息
     *
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HmProductBo bo)
    {
        HmProduct update = MapstructUtils.convert(bo, HmProduct.class);
        if (Boolean.TRUE.equals(bo.getIsCommercialProduct())) {
            update.setProductType("CP");
        }
        if (Boolean.TRUE.equals(bo.getIsGiftProduct())) {
            update.setProductType("ZP");
        }
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HmProduct entity)
    {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除产品信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     *
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid)
    {
        if (isValid)
        {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 通过产品ID查询产品是否为商品产品
     * @param productId 产品ID
     * @return true 如果是商品产品，否则 false
     */
    @Override
    public Boolean isCommercialProduct(Long productId) {
        HmProductVo hmProductVo = queryById(productId);
        return hmProductVo != null && Boolean.TRUE.equals(hmProductVo.getIsCommercialProduct());
    }

    /**
     * 通过产品ID查询产品是否为赠品产品
     * @param productId 产品ID
     * @return true 如果是赠品产品，否则 false
     */
    @Override
    public Boolean isGiftProduct(Long productId) {
        HmProductVo hmProductVo = queryById(productId);
        return hmProductVo != null && Boolean.TRUE.equals(hmProductVo.getIsGiftProduct());
    }

    /**
     * 通过产品ID查询产品的所有类型 (例如：["CP", "ZP"])
     * @param productId 产品ID
     * @return 产品类型列表
     */
    @Override
    public List<String> selectProductTypesById(Long productId) {
        HmProductVo hmProductVo = queryById(productId);
        List<String> types = new ArrayList<>();
        if (hmProductVo != null) {
            if (Boolean.TRUE.equals(hmProductVo.getIsCommercialProduct())) {
                types.add("CP");
            }
            if (Boolean.TRUE.equals(hmProductVo.getIsGiftProduct())) {
                types.add("ZP");
            }
        }
        return types;
    }

    /**
     * 通过产品ID查询产品名称
     *
     * @param productId 产品ID
     *
     * @return
     */
    @Override
    public String selectProductNameById(Long productId)
    {
        HmProductVo hmProductVo = queryById(productId);
        if (hmProductVo != null)
        {
            return hmProductVo.getProductName();
        }
        return "";
    }

    /**
     * 通过产品id查询产品类型
     * @param productId 产品id
     *
     * @return
     */

    @Override
    public String selectProductTypeByProductId(Long productId)
    {
        HmProductVo hmProductVo = queryById(productId);
        if (hmProductVo != null)
        {
            return hmProductVo.getProductType();
        }
        return "";
    }
}
